package com.edu.handler;

import com.alibaba.fastjson2.JSON;
import com.edu.commons.R;
import com.edu.commons.ServiceCode;
import com.edu.commons.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


@Configuration
@Order(-1) // 确保优先级高于默认的错误处理器
@Slf4j
public class GlobalErrorHandler implements ErrorWebExceptionHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        // 记录错误日志
        log.error("网关异常处理: 路径={}, 异常={}", exchange.getRequest().getPath(), ex.getMessage(), ex);

        // 构建统一响应格式
        R r = R.fail(new ServiceException(ServiceCode.ERROR_UN_AUTHORIZED,ex.getMessage()));

        // 设置响应头
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 写入响应体
        byte[] bytes = JSON.toJSONString(r).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}